﻿using System;
using System.Diagnostics;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.ServiceProcess;
using CommandLine;

namespace MyLib.ViewStateServer {
	/// <summary>
	/// 
	/// </summary>
	partial class MainService : ServiceBase {
		/// <summary>
		/// 
		/// </summary>
		private const string ROOT_CHANNEL_NAME = "root";

		public MainService() {
			InitializeComponent();
		}

		/// <summary>
		/// 
		/// </summary>
		public override EventLog EventLog {
			get {
				return eventLog1;
			}
		}

		private double m_timeout;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="args"></param>
		protected override void OnStart(string[] args) {
			var options = new CommandLineOptions();
			if (!Parser.Default.ParseArguments(args, options)) {
				eventLog1.WriteEntry(
					"Invalid arguments.\n\nUsage: <servicename> [-h | --host <hostname>] [-p | --port <port>] [--timeout <timeout> \n",
					EventLogEntryType.Error);
			}

			var channel = new TcpServerChannel(ROOT_CHANNEL_NAME, options.Port);
			ChannelServices.RegisterChannel(channel, false);
			m_timeout = options.Timeout;
		}

		/// <summary>
		/// 
		/// </summary>
		protected override void OnPause() {
			var channel = ChannelServices.GetChannel(ROOT_CHANNEL_NAME) as TcpServerChannel;
			if (channel != null) {
				channel.StopListening(null);
			}
			timer1.Stop();
		}

		/// <summary>
		/// 
		/// </summary>
		protected override void OnContinue() {
			var channel = ChannelServices.GetChannel(ROOT_CHANNEL_NAME) as TcpServerChannel;
			if (channel != null) {
				channel.StartListening(null);
			}
			timer1.Start();
		}

		/// <summary>
		/// 
		/// </summary>
		protected override void OnStop() {
			var channel = ChannelServices.GetChannel(ROOT_CHANNEL_NAME) as TcpServerChannel;
			if (channel != null) {
				ChannelServices.UnregisterChannel(channel);
			}
		}

		private void timer1_Tick(object sender, System.EventArgs e) {
			DataAdapter.ClearNouse(DateTime.Now.AddMinutes(-m_timeout));
		}
	} // end of MainService.
}
